# 拿到4399小游戏名称与链接
from lxml import etree
import requests
import csv

csv_filename = 'game_titles_links.csv'
# 创建CSV文件并写入标题行
with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(['Title', 'Link'])


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36',

}
for i in range(1, 11):
    url = 'https://www.4399.com/flash/new_{}.htm'.format(i)
    place = '//*[@id="skinbody"]/div[8]/ul/li'
    if i == 1:
        url = 'https://www.4399.com/flash/new.htm'
    else:
        place = '//*[@id="skinbody"]/div[6]/ul/li'
    resp = requests.get(url, headers=headers)

    resp.encoding = "gbk"
    tree = etree.HTML(resp.text)

    li_lis = tree.xpath(place)
    for li in li_lis:
        title = li.xpath('./a/b/text()')[0]
        link = li.xpath('./a/@href')[0]
        if "flash" in link:
            link = 'https://www.4399.com/' + link
        # print(title, link)
        with open(csv_filename, 'a', newline='', encoding='utf-8') as csvfile:
            writer = csv.writer(csvfile)
            writer.writerow([title, link])

